<template>
  <div class="head">
    <div class="title">
      <div>
        <el-form :inline="true" class="search-form" :model="searchForm" ref="ruleFormRef">
          <el-form-item label="产品名称/规格型号">
            <el-input
              v-model="searchForm.productName"
              placeholder="请输入产品名称/规格型号"
              style="width: 280px"
            />
          </el-form-item>
          <el-form-item label="制造商品牌">
            <el-input
              v-model="searchForm.productBrand"
              placeholder="请输入制造商品牌"
              style="width: 280px"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="props.ifEnd === '履行中'"
              type="primary"
              icon="Search"
              @click="getData"
            >
              搜索
            </el-button>
            <el-button v-if="props.ifEnd === '履行中'" @click="clear">重置</el-button>
            <el-button
              v-if="props.ifEnd === '履行中'"
              type="primary"
              icon="Download"
              @click="downloadFile"
            >
              模板下载
            </el-button>
            <el-upload
              ref="uploadRef"
              accept=".xlsx"
              class="upload-demo"
              :limit="1"
              :http-request="uploadFile"
              :before-upload="beforeUpload"
              v-model:file-list="fileList"
              style="width: 80px; margin-left: 12px"
            >
              <template #trigger>
                <el-button type="primary" icon="Upload" v-if="props.ifEnd === '履行中'"
                  >导入</el-button
                >
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table
      :data="TableData"
      style="width: 100%"
      ref="TableRef"
      @cell-click="getCell"
      border
      stripe
      v-loading="load"
    >
      <el-table-column label="序号" type="index" width="60">
        <template #default="scope">
          <div>{{ pageInfo.pageSize * (pageInfo.pageNum - 1) + scope.row.index + 1 }}</div>
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in columns"
        :key="item"
        :label="item.label"
        :width="item.width"
        :prop="item.prop"
      >
        <template #default="scope">
          <el-input
            v-model="scope.row[item.prop]"
            ref="tabInput"
            :type="item?.type"
            @blur="inputBlur"
            :min="0"
            maxlength="64"
            show-word-limit
            v-if="scope.row.index == tabRowIndex && scope.column.no == tabColumnIndex"
          />
          <div v-else>{{ scope.row[item.prop] }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        width="110"
        v-if="props.ifEnd === '履行中'"
      >
        <template #default="scope">
          <el-button icon="Delete" type="danger" @click="del(scope.row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex; justify-content: center; margin-top: 20px">
      <el-pagination
        v-model:currentPage="pageInfo.pageNum"
        :page-size="pageInfo.pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, nextTick, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    postPaymentProductUploadExcel,
    postPaymentProductSearch,
    putPaymentProduct,
    deletePaymentProductById,
  } from '@/api/controller/payment-product-controller/index'
  import {
    postCollectionProductUploadExcel,
    postCollectionProductSearch,
    putCollectionProduct,
    deleteCollectionProductById,
  } from '@/api/controller/collection-product-controller/index'

  let props = defineProps({
    ifEnd: {
      type: String,
    },
  })

  const load = ref(false)
  const contractId = ref(history.state?.contractId)
  const contractType = ref(history.state?.contractType)
  //模板文件下载
  const downloadFile = () => {
    window.open('/model.xlsx')
  }

  const fileList = ref([])
  //上传导入模板文件
  const uploadFile = async () => {
    const file = new FormData()
    file.append('file', fileList.value[0].raw)
    fileList.value = []
    let res
    if (contractType.value === '1') {
      res = await postCollectionProductUploadExcel({ contractId: contractId.value }, file, {
        loading: true,
      })
    } else {
      res = await postPaymentProductUploadExcel({ contractId: contractId.value }, file, {
        loading: true,
      })
    }
    let b = new Blob([res]) //拿到文件流下载对象
    let url = window.URL.createObjectURL(b) //生成文件流下载链接
    let a = document.createElement('a') //创建一个a标签用来跳转
    a.href = url // a标签 href  赋值 链接
    a.download = '上传结果.txt' //设置下载文件的文件名和文件格式
    document.body.appendChild(a) //将标签DOM，放置页面
    a.click()
    window.URL.revokeObjectURL(url) //释放 url 对象内存
    document.body.removeChild(a) //移除标签节点
    getData()
  }
  const beforeUpload = (file) => {
    const { name } = file
    //   文件类型限制
    const fileTypeFlag = /^.xlsx$/.test(name.substring(name.lastIndexOf('.')).toLowerCase())
    if (!fileTypeFlag) {
      ElMessage.warning('文件类型只能是.xlsx')
      return false
    }
  }

  const columns = ref([
    { label: '产品名称', prop: 'productName' },
    { label: '制造商品牌', prop: 'productBrand' },
    { label: '规格型号', prop: 'productModel' },
    { label: '数量', prop: 'productNumber', type: 'number', width: '100' },
    { label: '单位', prop: 'productUnit', width: '80' },
    { label: '单价(元)', prop: 'productPrice', type: 'number', width: '100', moneyType: true },
    { label: '税率(%)', prop: 'productTax', type: 'number', width: '80' },
    { label: '总价(元)', prop: 'productWholePrice', type: 'number', width: '110', moneyType: true },
    { label: '备注', prop: 'remark' },
  ])
  const TableData = ref([])

  const tabRowIndex = ref()
  const tabColumnIndex = ref()
  const tabInput = ref()
  const total = ref(0)
  const pageInfo = ref({
    pageNum: 1,
    pageSize: 10,
  })
  const searchForm = ref({ productName: '', productBrand: '' })

  //获取数据
  const getData = async () => {
    try {
      load.value = true
      let res
      if (contractType.value === '1') {
        res = await postCollectionProductSearch({
          ...searchForm.value,
          ...pageInfo.value,
          ...{ contractId: contractId.value },
        })
      } else {
        res = await postPaymentProductSearch({
          ...searchForm.value,
          ...pageInfo.value,
          ...{ contractId: contractId.value },
        })
      }
      if (res.code === 200) {
        TableData.value = res.data.list
        TableData.value.forEach((item, index) => {
          item.index = index
        })
        total.value = res.data.total
      }
    } finally {
      load.value = false
    }
  }
  //清空搜索框
  const clear = () => {
    searchForm.value = { productName: '', productBrand: '' }
    getData()
  }
  onMounted(() => {
    pageInfo.value = {
      pageNum: 1,
      pageSize: 10,
    }
  })
  //监听单击单元格
  const getCell = (row, column) => {
    tabRowIndex.value = row.index
    tabColumnIndex.value = column.no
    //点击单元格的时候聚焦输入框
    nextTick(() => {
      tabInput.value[0].focus()
    })
  }

  //表格输入框失焦监听
  const inputBlur = async () => {
    let a = tabRowIndex.value
    tabRowIndex.value = null
    tabColumnIndex.value = ''
    let res
    if (TableData.value[a]) {
      if (contractType.value === '1') {
        res = await putCollectionProduct(TableData.value[a])
      } else {
        res = await putPaymentProduct(TableData.value[a])
      }
      if (res.code === 200) {
        getData()
      }
    }
  }

  //删除
  const del = (row) => {
    ElMessageBox.confirm('你确定要删除当前项吗?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(async () => {
        let result
        if (contractType.value === '1') {
          result = await deleteCollectionProductById({ id: row.id })
        } else {
          result = await deletePaymentProductById({ id: row.id })
        }
        if (result.code === 200) {
          getData()
          ElMessage.success('删除成功')
        }
      })
      .catch(() => {
        console.log('错误')
      })
  }
  //分页
  const handleSizeChange = (val) => {
    pageInfo.value.pageSize = val
    pageInfo.value.pageNum = 1
    getData()
  }
  const handleCurrentChange = () => {
    getData()
  }
</script>

<style lang="scss" scoped>
  .title {
    margin-bottom: 10px;
    span {
      font-size: 16px;
      font-weight: 700;
    }
  }
  .head {
    background-color: white;
    margin: 0;
    padding: 20px;
  }
  :deep(.el-upload-list) {
    display: none;
  }
  :deep(input::-webkit-outer-spin-button),
  :deep(input::-webkit-inner-spin-button) {
    -webkit-appearance: none !important;
  }
</style>
